package org.qydjk.common.util;

import java.io.*;

/**
 * Created by Administrator on 2017/12/29 0029.
 */
public class FileUtil {
    /**
     * 从项目配置文件夹读取字符串
     * @param filePath
     * @return
     */
    public static String readFromSysPath(String filePath){
        if(StringUtil.isEmptyOrNull(filePath)){
            return null;
        }
        File file = new File(FileUtil.class.getResource(filePath).getPath());
        return read(file);
    }

    /**
     * 从文件读取字符串
     * @param filePath
     * @return
     */
    public static String read(String filePath){
        if(StringUtil.isEmptyOrNull(filePath)){
            return null;
        }
        File file = new File(filePath);
        return read(file);
    }

    /**
     * 从文件读取字符串
     * @param file
     * @return
     */
    public static String read(File file){
        String str="";
        try {
            FileInputStream in=new FileInputStream(file);
            // size  为字串的长度 ，这里一次性读完
            int size=in.available();
            byte[] buffer=new byte[size];
            in.read(buffer);
            in.close();
            str=new String(buffer,"utf-8");
            return str;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 复制单个文件
     * @param oldPathFile 准备复制的文件源
     * @param newPathFile 拷贝到新绝对路径带文件名
     * @return
     */
    public static void copyFile(String oldPathFile, String newPathFile) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPathFile);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPathFile); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPathFile);
                byte[] buffer = new byte[1444];
                while((byteread = inStream.read(buffer)) != -1){
                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建目录
     * @param dir_path
     */
    public static void mkDir(String dir_path) {
        File myFolderPath = new File(dir_path);
        try {
            if (!myFolderPath.exists()) {
                myFolderPath.mkdir();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建文件
     * @param file_path
     */
    public static void createNewFile(String file_path) {
        File myFilePath = new File(file_path);
        try {
            if (!myFilePath.exists()) {
                myFilePath.createNewFile();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

}
